// Web版本的API客户端
class APIClient {
    async invoke(method, ...args) {
        const response = await fetch(`/api/${method}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(args.length === 1 ? args[0] : args)
        });
        
        if (!response.ok) {
            throw new Error(`API调用失败: ${response.statusText}`);
        }
        
        const result = await response.json();
        if (!result.success) {
            throw new Error(result.error || 'API调用失败');
        }
        
        // For export-to-word, return the full result, not just result.data
        if (method === 'export-to-word') {
            return result;
        }
        
        return result.data;
    }
    
    async get(endpoint) {
        const response = await fetch(`/api/${endpoint}`);
        if (!response.ok) {
            throw new Error(`API调用失败: ${response.statusText}`);
        }
        
        const result = await response.json();
        if (!result.success) {
            throw new Error(result.error || 'API调用失败');
        }
        
        return result.data;
    }
}

// 创建API客户端实例
const ipcRenderer = new APIClient();

class AI2WordApp {
    constructor() {
        this.currentTopic = null;
        this.quillEditor = null;
        this.settings = {};
        this.isGenerating = false;
        
        this.init();
    }

    async init() {
        this.setupEventListeners();
        this.initializeQuillEditor();
        await this.loadSettings();
        await this.loadHistoricalTopics();
        await this.loadArticleHistory();
    }

    setupEventListeners() {
        // 导航标签切换
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.addEventListener('click', (e) => {
                this.switchTab(e.target.dataset.tab);
            });
        });

        // 主题管理
        document.getElementById('use-manual-topic').addEventListener('click', () => {
            this.useManualTopic();
        });

        document.getElementById('generate-topics').addEventListener('click', () => {
            this.generateTopics();
        });

        // 内容生成
        document.getElementById('generate-article').addEventListener('click', () => {
            this.generateArticle();
        });

        document.getElementById('stop-generation').addEventListener('click', () => {
            this.stopGeneration();
        });

        document.getElementById('regenerate').addEventListener('click', () => {
            this.regenerateArticle();
        });

        document.getElementById('export-word').addEventListener('click', () => {
            this.exportToWord();
        });

        // 历史记录
        document.getElementById('refresh-history').addEventListener('click', () => {
            this.loadArticleHistory();
        });

        document.getElementById('history-search').addEventListener('input', (e) => {
            this.searchHistory(e.target.value);
        });

        // 设置
        document.getElementById('save-settings').addEventListener('click', () => {
            this.saveSettings();
        });

        document.getElementById('reset-settings').addEventListener('click', () => {
            this.resetSettings();
        });

        // 模态框
        document.querySelector('.modal-close').addEventListener('click', () => {
            this.hideModal();
        });

        document.getElementById('modal-cancel').addEventListener('click', () => {
            this.hideModal();
        });

        // 主题切换
        document.getElementById('theme').addEventListener('change', (e) => {
            this.applyTheme(e.target.value);
        });
    }

    initializeQuillEditor() {
        const editorContainer = document.getElementById('article-editor');
        
        // 清空占位符
        editorContainer.innerHTML = '';
        
        this.quillEditor = new Quill(editorContainer, {
            theme: 'snow',
            modules: {
                toolbar: [
                    [{ 'header': [1, 2, 3, false] }],
                    ['bold', 'italic', 'underline'],
                    [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                    ['code-block'],
                    ['clean']
                ]
            },
            placeholder: '请选择主题并点击"生成文章"开始创作...'
        });
    }

    switchTab(tabName) {
        // 更新导航标签
        document.querySelectorAll('.nav-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

        // 显示对应内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-tab`).classList.add('active');
    }

    async useManualTopic() {
        const topicInput = document.getElementById('manual-topic');
        const topic = topicInput.value.trim();
        
        if (!topic) {
            this.showMessage('请输入主题', 'error');
            return;
        }

        this.currentTopic = {
            title: topic,
            source: 'manual',
            id: Date.now()
        };

        // 保存到数据库
        try {
            await ipcRenderer.invoke('save-topic', this.currentTopic);
        } catch (error) {
            console.warn('保存主题失败:', error);
        }

        // 切换到生成页面
        this.switchTab('generate');
        this.updateCurrentTopicDisplay();
        
        topicInput.value = '';
        this.showMessage('主题已设置，可以开始生成文章', 'success');
    }

    async generateTopics() {
        const button = document.getElementById('generate-topics');
        const container = document.getElementById('recommended-topics');
        
        button.disabled = true;
        button.textContent = '生成中...';
        container.innerHTML = '<div class="loading-placeholder">正在生成推荐主题...</div>';

        try {
            const preferences = {
                techFields: '前端开发、后端开发、人工智能、云计算',
                difficulty: '中级',
                interests: '新技术趋势、最佳实践、性能优化'
            };

            const topics = await ipcRenderer.invoke('generate-topics', preferences);
            this.displayTopics(topics, container);
            
        } catch (error) {
            console.error('生成主题失败:', error);
            container.innerHTML = '<div class="loading-placeholder">生成主题失败，请检查网络连接和API配置</div>';
            this.showMessage('生成主题失败，请检查设置', 'error');
        } finally {
            button.disabled = false;
            button.textContent = 'AI推荐主题';
        }
    }

    displayTopics(topics, container) {
        if (!topics || topics.length === 0) {
            container.innerHTML = '<div class="loading-placeholder">暂无推荐主题</div>';
            return;
        }

        container.innerHTML = topics.map(topic => `
            <div class="topic-card" data-topic-id="${topic.id}">
                <div class="topic-title">${topic.title}</div>
                <div class="topic-meta">
                    来源: ${topic.source === 'ai_generated' ? 'AI推荐' : '手动输入'} | 
                    创建时间: ${new Date(topic.created_at || topic.createdAt).toLocaleString()}
                </div>
            </div>
        `).join('');

        // 添加点击事件
        container.querySelectorAll('.topic-card').forEach(card => {
            card.addEventListener('click', () => {
                this.selectTopic(topics.find(t => t.id == card.dataset.topicId));
            });
        });
    }

    selectTopic(topic) {
        this.currentTopic = topic;
        
        // 更新视觉反馈
        document.querySelectorAll('.topic-card').forEach(card => {
            card.classList.remove('selected');
        });
        document.querySelector(`[data-topic-id="${topic.id}"]`).classList.add('selected');
        
        // 切换到生成页面
        this.switchTab('generate');
        this.updateCurrentTopicDisplay();
        
        this.showMessage('主题已选择，可以开始生成文章', 'success');
    }

    updateCurrentTopicDisplay() {
        const display = document.getElementById('current-topic');
        if (this.currentTopic) {
            display.textContent = this.currentTopic.title;
            display.className = 'current-topic';
        } else {
            display.textContent = '请先选择主题';
            display.className = 'current-topic placeholder';
        }
    }

    async generateArticle() {
        if (!this.currentTopic) {
            this.showMessage('请先选择主题', 'error');
            return;
        }

        if (!this.settings.api_key) {
            this.showMessage('请先在设置中配置API密钥', 'error');
            this.switchTab('settings');
            return;
        }

        const options = {
            length: document.getElementById('article-length').value,
            style: document.getElementById('writing-style').value,
            keywords: document.getElementById('keywords').value.split(',').map(k => k.trim()).filter(k => k),
            includeCode: document.getElementById('include-code').checked
        };

        this.startGeneration();

        try {
            const article = await ipcRenderer.invoke('generate-article', { topic: this.currentTopic.title, options });
            
            // 显示生成的文章
            this.quillEditor.setContents([]);
            this.quillEditor.clipboard.dangerouslyPasteHTML(article.content);
            
            // 启用操作按钮
            document.getElementById('regenerate').disabled = false;
            document.getElementById('export-word').disabled = false;
            
            // 自动保存
            if (this.settings.auto_save === 'true') {
                await this.saveCurrentArticle(article);
            }
            
            this.showMessage('文章生成成功', 'success');
            
        } catch (error) {
            console.error('生成文章失败:', error);
            this.showMessage('生成文章失败，请检查网络连接和API配置', 'error');
        } finally {
            this.stopGeneration();
        }
    }

    startGeneration() {
        this.isGenerating = true;
        document.getElementById('generate-article').disabled = true;
        document.getElementById('stop-generation').disabled = false;
        document.getElementById('generation-status').style.display = 'block';
        
        // 启动进度动画
        const progressFill = document.querySelector('.progress-fill');
        progressFill.style.animation = 'progress-animation 2s infinite';
    }

    stopGeneration() {
        this.isGenerating = false;
        document.getElementById('generate-article').disabled = false;
        document.getElementById('stop-generation').disabled = true;
        document.getElementById('generation-status').style.display = 'none';
    }

    async regenerateArticle() {
        if (this.currentTopic) {
            await this.generateArticle();
        }
    }

    async exportToWord() {
        if (!this.quillEditor.getLength() || this.quillEditor.getLength() <= 1) {
            this.showMessage('没有内容可导出', 'error');
            return;
        }

        try {
            const content = {
                title: this.currentTopic ? this.currentTopic.title : '技术文章',
                content: this.quillEditor.root.innerHTML
            };

            const filename = `${content.title.replace(/[^\w\s]/gi, '')}.docx`;
            const result = await ipcRenderer.invoke('export-to-word', { content, filename });
            
            this.showMessage(`文档已导出到: ${result.filePath}`, 'success');
            
        } catch (error) {
            console.error('导出失败:', error);
            this.showMessage('导出Word文档失败', 'error');
        }
    }

    async saveCurrentArticle(article) {
        try {
            const articleData = {
                title: article.title || this.currentTopic.title,
                content: this.quillEditor.root.innerHTML,
                topic: this.currentTopic.title,
                wordCount: article.wordCount || this.countWords(this.quillEditor.getText()),
                style: document.getElementById('writing-style').value,
                length: document.getElementById('article-length').value,
                keywords: document.getElementById('keywords').value
            };

            await ipcRenderer.invoke('save-article', articleData);
            
        } catch (error) {
            console.error('保存文章失败:', error);
        }
    }

    async loadHistoricalTopics() {
        try {
            const topics = await ipcRenderer.get('topics');
            const container = document.getElementById('historical-topics');
            
            if (topics && topics.length > 0) {
                this.displayTopics(topics, container);
            } else {
                container.innerHTML = '<div class="loading-placeholder">暂无历史主题</div>';
            }
            
        } catch (error) {
            console.error('加载历史主题失败:', error);
        }
    }

    async loadArticleHistory() {
        try {
            const articles = await ipcRenderer.get('article-history');
            const container = document.getElementById('article-history');
            
            if (articles && articles.length > 0) {
                this.displayArticleHistory(articles, container);
            } else {
                container.innerHTML = '<div class="loading-placeholder">暂无历史文章</div>';
            }
            
        } catch (error) {
            console.error('加载文章历史失败:', error);
            const container = document.getElementById('article-history');
            container.innerHTML = '<div class="loading-placeholder">加载失败</div>';
        }
    }

    displayArticleHistory(articles, container) {
        container.innerHTML = articles.map(article => `
            <div class="history-item" data-article-id="${article.id}">
                <div class="history-title">${article.title}</div>
                <div class="history-meta">
                    <span>主题: ${article.topic || '未知'}</span>
                    <span>字数: ${article.word_count || article.wordCount || 0}</span>
                    <span>创建时间: ${new Date(article.created_at).toLocaleString()}</span>
                </div>
                <div class="history-actions">
                    <button class="btn btn-primary btn-sm" onclick="app.loadArticle('${article.id}')">编辑</button>
                    <button class="btn btn-success btn-sm" onclick="app.exportHistoryArticle('${article.id}')">导出</button>
                    <button class="btn btn-danger btn-sm" onclick="app.deleteArticle('${article.id}')">删除</button>
                </div>
            </div>
        `).join('');
    }

    async loadArticle(id) {
        try {
            const response = await fetch(`/api/article/${id}`);
            const result = await response.json();
            
            if (result.success) {
                const article = result.data;
                this.quillEditor.clipboard.dangerouslyPasteHTML(article.content);
                this.currentTopic = { title: article.topic };
                this.updateCurrentTopicDisplay();
                this.switchTab('generate');
                
                // 恢复生成参数
                document.getElementById('article-length').value = article.length || 'normal';
                document.getElementById('writing-style').value = article.style || 'professional';
                document.getElementById('keywords').value = article.keywords || '';
                
                document.getElementById('regenerate').disabled = false;
                document.getElementById('export-word').disabled = false;
            }
        } catch (error) {
            console.error('加载文章失败:', error);
            this.showMessage('加载文章失败', 'error');
        }
    }

    async exportHistoryArticle(id) {
        try {
            const response = await fetch(`/api/article/${id}`);
            const result = await response.json();
            
            if (result.success) {
                const article = result.data;
                const content = {
                    title: article.title,
                    content: article.content
                };
                const filename = `${article.title.replace(/[^\w\s]/gi, '')}.docx`;
                const exportResult = await ipcRenderer.invoke('export-to-word', { content, filename });
                
                this.showMessage(`文档已导出到: ${exportResult.filePath}`, 'success');
            }
        } catch (error) {
            console.error('导出历史文章失败:', error);
            this.showMessage('导出失败', 'error');
        }
    }

    async deleteArticle(id) {
        if (confirm('确定要删除这篇文章吗？')) {
            try {
                const response = await fetch(`/api/article/${id}`, { method: 'DELETE' });
                const result = await response.json();
                
                if (result.success) {
                    this.loadArticleHistory();
                    this.showMessage('文章已删除', 'success');
                }
            } catch (error) {
                console.error('删除文章失败:', error);
                this.showMessage('删除失败', 'error');
            }
        }
    }

    searchHistory(query) {
        const items = document.querySelectorAll('.history-item');
        items.forEach(item => {
            const title = item.querySelector('.history-title').textContent.toLowerCase();
            const topic = item.querySelector('.history-meta').textContent.toLowerCase();
            
            if (title.includes(query.toLowerCase()) || topic.includes(query.toLowerCase())) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    }

    async loadSettings() {
        try {
            this.settings = await ipcRenderer.get('settings');
            
            // 更新界面
            document.getElementById('ai-provider').value = this.settings.ai_provider || 'openai';
            document.getElementById('api-key').value = this.settings.api_key || '';
            document.getElementById('api-base-url').value = this.settings.api_base_url || '';
            document.getElementById('default-style').value = this.settings.default_style || 'professional';
            document.getElementById('default-length').value = this.settings.default_length || 'normal';
            document.getElementById('auto-save').checked = this.settings.auto_save === 'true';
            document.getElementById('theme').value = this.settings.theme || 'light';
            
            // 应用主题
            this.applyTheme(this.settings.theme || 'light');
            
            // 更新生成页面的默认值
            document.getElementById('writing-style').value = this.settings.default_style || 'professional';
            document.getElementById('article-length').value = this.settings.default_length || 'normal';
            
        } catch (error) {
            console.error('加载设置失败:', error);
        }
    }

    async saveSettings() {
        try {
            const newSettings = {
                ai_provider: document.getElementById('ai-provider').value,
                api_key: document.getElementById('api-key').value,
                api_base_url: document.getElementById('api-base-url').value,
                default_style: document.getElementById('default-style').value,
                default_length: document.getElementById('default-length').value,
                auto_save: document.getElementById('auto-save').checked ? 'true' : 'false',
                theme: document.getElementById('theme').value
            };

            await ipcRenderer.invoke('save-settings', newSettings);
            this.settings = { ...this.settings, ...newSettings };
            
            this.showMessage('设置已保存', 'success');
            
        } catch (error) {
            console.error('保存设置失败:', error);
            this.showMessage('保存设置失败', 'error');
        }
    }

    resetSettings() {
        if (confirm('确定要重置所有设置吗？')) {
            document.getElementById('ai-provider').value = 'openai';
            document.getElementById('api-key').value = '';
            document.getElementById('api-base-url').value = '';
            document.getElementById('default-style').value = 'professional';
            document.getElementById('default-length').value = 'normal';
            document.getElementById('auto-save').checked = true;
            document.getElementById('theme').value = 'light';
            
            this.applyTheme('light');
        }
    }

    applyTheme(theme) {
        if (theme === 'dark') {
            document.body.classList.add('dark-theme');
        } else {
            document.body.classList.remove('dark-theme');
        }
    }

    showMessage(message, type = 'info') {
        // 简单的消息提示实现
        const messageDiv = document.createElement('div');
        messageDiv.className = `message message-${type}`;
        messageDiv.textContent = message;
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            border-radius: 4px;
            color: white;
            z-index: 1001;
            background-color: ${type === 'error' ? '#e74c3c' : type === 'success' ? '#27ae60' : '#3498db'};
        `;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            messageDiv.remove();
        }, 3000);
    }

    showModal(title, content, onConfirm = null) {
        document.getElementById('modal-title').textContent = title;
        document.getElementById('modal-body').innerHTML = content;
        document.getElementById('modal').style.display = 'flex';
        
        if (onConfirm) {
            document.getElementById('modal-confirm').onclick = () => {
                onConfirm();
                this.hideModal();
            };
        }
    }

    hideModal() {
        document.getElementById('modal').style.display = 'none';
    }

    countWords(text) {
        return text.replace(/[^\u4e00-\u9fa5]/g, '').length;
    }
}

// 初始化应用
const app = new AI2WordApp();

// 全局错误处理
window.addEventListener('error', (e) => {
    console.error('应用错误:', e.error);
});

window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise拒绝:', e.reason);
});